﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace SF.Base.Core {
	public class BasePage : System.Web.UI.Page {
		public BasePage() {
			this.PreRender += new EventHandler(RefreshPage_PreRender);
		}

		public string EncodeToHtml(string source){
			return StringHelper.EncodeToHtml(source);
		}

		private void RefreshPage_PreRender(object sender, EventArgs e) {
			if (Session["RefreshTicketCounter"] == null)
				Session["RefreshTicketCounter"] = 0;

			int ticket = Convert.ToInt32(Session["RefreshTicketCounter"]) + 1;
			ClientScript.RegisterHiddenField("__CURRENTREFRESHTICKET", ticket.ToString());
		}

		/// <summary>
		/// 是否是F5刷新
		/// </summary>
		public bool IsPageRefresh {
			get {
				object o = HttpContext.Current.Items["IsPageRefresh"];
				if (o == null)
					return false;
				return (bool)o;
			}
		}

		/// <summary>
		/// 重置刷新状态
		/// </summary>
		public void TrackRefreshState() {
			if (Session["RefreshTicketCounter"] == null)
				Session["RefreshTicketCounter"] = 0;

			int ticket = Convert.ToInt32(Session["RefreshTicketCounter"]) + 1;
			Session["RefreshTicketCounter"] = ticket;
		}

		#region 重写基类方法

		/// <summary>
		/// 重写OnError方法
		/// </summary>
		/// <param name="e"></param>
		protected override void OnError(EventArgs e) {
			Exception ex = Server.GetLastError();
			if (ex != null) {
				Logger.Exception(ex);

				//Server.ClearError();

				//Response.Redirect(WebHelper.RootPath() + "ErrorPage.aspx?msg=" + HttpUtility.UrlEncode(ex.Message), false);
			}
		}

		/// <summary>
		/// 重写OnLoad方法
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			if (!ClientScript.IsClientScriptBlockRegistered("useridblock")) {
				ClientScript.RegisterClientScriptBlock(Page.GetType(), "useridblock", string.Format("var userid = '{0}' ;", UID), true);
			}
		}

		#endregion

		protected long UID {
			get {
				if (HttpContext.Current.Session["_DT_USER_"] == null) {
					return -1;
				}
				return (HttpContext.Current.Session["_DT_USER_"] as UserEntity).UID;
			}
		}

		protected string UserId {
			get {
				if (HttpContext.Current.Session["_DT_USER_"] == null) {
					return Guid.Empty.ToString();
				}
				return (HttpContext.Current.Session["_DT_USER_"] as UserEntity).UserId.ToString();
			}
		}
	}
}
